#ifndef NETWORKCONTROLLER_H
#define NETWORKCONTROLLER_H

#include <QObject>
#include <QMutex>
#include <QByteArray>
#include <QUdpSocket>
#include <QTimer>
#include <QHostAddress>
#include <QNetworkReply>
#include <QNetworkAccessManager>
#include <QJsonObject>
#include <QJsonDocument>

class NetworkController : public QObject
{
    Q_OBJECT

public:
    explicit NetworkController(QObject *parent = nullptr);
    ~NetworkController();

    enum DeviceType {
        Display1 = 0,
        Display2 = 1
    };

    // 网络配置
    struct NetworkConfig {
        QString deviceIP;
        quint16 devicePort;
        int timeout;
        int retryCount;
    };

    bool initializeNetwork();
    bool sendToDisplay(int displayIndex, const QByteArray &data);
    void setDisplayResolution(int width, int height);
    void setColorDepth(int bits);
    
    // 设备管理
    bool addDevice(int deviceIndex, const QString &ip, quint16 port);
    bool removeDevice(int deviceIndex);
    bool pingDevice(int deviceIndex);
    
    // 网络状态
    bool isDeviceOnline(int deviceIndex);
    QString getDeviceStatus(int deviceIndex);

signals:
    void networkError(const QString &error);
    void dataTransmitted(int displayIndex, int bytes);
    void deviceStatusChanged(int deviceIndex, bool online);
    void deviceDiscovered(const QString &ip, int deviceIndex);

public slots:
    void discoverDevices();
    void checkDeviceStatus();

private slots:
    void handleUdpResponse();
    void handleHttpResponse();
    void onDiscoveryTimeout();

private:
    // 网络通信
    bool sendUdpCommand(int deviceIndex, const QJsonObject &command);
    bool sendHttpCommand(int deviceIndex, const QJsonObject &command);
    QJsonObject createDisplayCommand(const QByteArray &data);
    QJsonObject createConfigCommand(const QString &param, const QVariant &value);
    QJsonObject createStatusCommand();
    
    // 设备发现
    void broadcastDiscovery();
    void parseDiscoveryResponse(const QByteArray &data, const QHostAddress &sender);
    
    // 设备管理
    bool initializeDevice(int deviceIndex);
    void configureDevice(int deviceIndex);
    
    // UDP通信
    QUdpSocket *m_udpSocket;
    QMap<int, NetworkConfig> m_devices;
    
    // HTTP通信 (备用)
    QNetworkAccessManager *m_networkManager;
    
    // 状态管理
    QTimer *m_discoveryTimer;
    QTimer *m_statusTimer;
    QMap<int, bool> m_deviceStatus;
    QMap<int, QDateTime> m_lastResponse;
    
    // 配置
    int m_displayWidth;
    int m_displayHeight;
    int m_colorDepth;
    bool m_isInitialized;
    
    // 线程安全
    QMutex m_networkMutex;
    
    // 常量
    static const quint16 DEFAULT_DISCOVERY_PORT;
    static const quint16 DEFAULT_DEVICE_PORT;
    static const int DEFAULT_TIMEOUT;
    static const int NETWORK_MAX_RETRY_COUNT;
    static const QString DISCOVERY_MESSAGE;
    static const QString DEVICE_TYPE_HI3861;
};

#endif // NETWORKCONTROLLER_H 